package com.world.rickcloudendpoint.service.net.session;

import com.world.rickcloudendpoint.common.constant.DetailErrorCodes;
import com.world.rickcloudendpoint.common.constant.ErrorCodes;
import com.world.rickcloudendpoint.common.exception.NetMessageException;
import com.world.rickcloudendpoint.message.AbstractNetMessage;
import io.netty.channel.Channel;
import lombok.extern.log4j.Log4j2;

/**
 * @description: Tcp 网络协议消息发送者
 * @author: jlsong
 * @date: 2021/12/24 21:12:41
 * @version: 1.0
 */
@Log4j2
public class TcpNetMessageSender implements INetMessageSender {

    private final NetSession netSession;

    public TcpNetMessageSender(NetSession netSession) {
        this.netSession = netSession;
    }

    @Override
    public boolean sendMessage(AbstractNetMessage message) throws NetMessageException {
        try {
            netSession.write(message);
        } catch (Exception e) {
            // 增加session 消息输出的错误日志
            log.error("Send message failed, the reason is {} ", e.getMessage(), e);
            throw new NetMessageException(ErrorCodes.getApplicationUi(DetailErrorCodes.Net_Protocol_Not_Supported.value()), String.format("write tcp net message exception: %s ", e.getMessage()));
        }
        return true;
    }

    @Override
    public void close() throws NetMessageException {
        Channel channel = netSession.channel;
        channel.close();
    }
}
